# coding = utf-8
from shopping.models import Category, Goods, GoodsImage, GiftPackage
from rest_framework import serializers

from rest_framework.serializers import ModelSerializer


class CategorySerializer(ModelSerializer):
    """
    分类
    """
    is_show_name = serializers.CharField(source='get_is_show_display', read_only=True)

    class Meta:
        model = Category
        exclude = ["update_time", "add_time"]


class GoodsImageSerializer(ModelSerializer):
    """
    商品图片
    """
    class Meta:
        model = GoodsImage
        exclude = ["update_time", "add_time"]


class GoodsListSerializer(ModelSerializer):
    """
    商品列表
    """
    class Meta:
        model = Goods
        fields = ["id", "name"]


class GoodsSerializer(ModelSerializer):
    """
    商品管理
    """
    category_name = serializers.CharField(source='category.name', read_only=True)
    drop_name = serializers.CharField(source='get_drop_display', read_only=True)
    title_image = serializers.SerializerMethodField(read_only=True)
    images = GoodsImageSerializer(many=True, read_only=True)

    class Meta:
        model = Goods
        exclude = ["update_time", "add_time"]

    def get_title_image(self, obj):
        image = obj.images.first()
        if image and image.image:
            return image.image.url

        return None


class WxGoodsSerializer(ModelSerializer):
    """
    商品管理
    """
    title_image = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Goods
        fields = ["id", "name", "desc", "title_image", "sn"]

    def get_title_image(self, obj):
        image = obj.images.first()
        if image and image.image:
            return image.image.url

        return None


class GiftPackageSerializer(ModelSerializer):
    """
    礼包
    """
    goods_list = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = GiftPackage
        exclude = ["update_time", "add_time"]

    def get_goods_list(self, obj):
        qs = obj.goods.values("name")
        lists = [item.get("name") for item in qs]
        return ", ".join(lists)


class WxGiftPackageSerializer(ModelSerializer):
    """
    礼包
    """
    goods = WxGoodsSerializer(many=True)

    class Meta:
        model = GiftPackage
        exclude = ["update_time", "add_time"]

